package gazzera.node.core.plugins.trust;

import gazzera.node.core.peer.*;

import java.util.*;


/**
 * This maps our trust network.
 * Basically it contains a map of trusted nodes and their friends:
 * Trusted -> Set of common trusting friends.
 *
 */
public class TrustNet
{
	private Map<Node, Set<String>> net = new HashMap<Node, Set<String>>();
	
	public void add(Node from, String hash)
	{
		Set<String> gids = net.get(from);
		if(gids == null)
		{
			gids = new HashSet<String>();
			net.put(from, gids);
		}
		gids.add(hash);
	}
	
	public boolean remove(Node from, String hash)
	{
		Set<String> gids = net.get(from);
		if(gids != null)
		{
			gids.remove(hash);
			if(gids.isEmpty())
			{
				net.remove(from);
			}
		}
		return !isConnectable(hash);
	}
	public Set<String> removeTrusted(Node n)
	{
		Set<String> r = net.get(n);
		net.remove(n);
		return r;
	}
	/**
	 * Returns true if there's at least one trusted node that have this person in the common trusting friends.
	 * @param hash
	 * @return
	 */
	public boolean isConnectable(String hash)
	{
		for (Set<String> s : net.values())
		{
			if(s.contains(hash)) return true;
		}
		return false;
	}
}